/*
 * Copyright (C) 2015 truth
 *
 * This program is non-free software, but you can redistribute it and/or modify
 * it if you are in hjj(Huangshi Hejianjiao) team.
 */
package com.truthbean.jutils.dao.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @since Jan 15, 2015 11:18:31 AM
 * @author TruthBean
 */
public class Connector {

    private static DataSource dataSource = null;

    static {
        //c3p0数据源
        dataSource = new ComboPooledDataSource("c3p0");
    }

    public static Connection getConn() {
        try {
            /**
             * 从数据连接池中获取连接
             */
            return dataSource.getConnection();
        } catch (SQLException e) {
            Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, "数据库连接错误！", e);
            return null;
        }
    }

    /**
     * 关闭dao内的方法的ResultSet, PreparedStatement 注意关闭的顺序
     * @param rs
     * @param ps
     */
    public static void close(ResultSet rs, PreparedStatement ps) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            rs = null;//如果ResultSet设为全局变量的话，必须将其致空
            Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, "ResultSet关闭失败!", e);
        } finally {
            try {
                if (ps != null) {
                    ps.close();
                }
            } catch (SQLException e) {
                ps = null;//如果PreparedStatement设为全局变量的话，必须将其致空
                Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, "PreparedStatement关闭失败!", e);
            }
        }
    }

    public static void release(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                conn = null;
                Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, "数据库连接关闭失败!", e);
            }
        }
    }
}
